package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"storehose/models"
	"strconv"
)

type StoreController struct {
	beego.Controller
}
type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *StoreController) List1() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "get,post")
	var store []models.Store
	err := models.DB.Order("sum desc").Find(&store).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功",
			Data: store,
		}
		c.ServeJSON()
	}
}
func (c *StoreController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 3)
	keys := "page-" + strconv.Itoa(page) + "-" + strconv.Itoa(pageSize)
	val, err := models.Rdb.Get(keys).Result()
	pageData := make(map[string]interface{})
	if err != nil {
		store, total, err := models.Page(page, pageSize)
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
		}
		pageData["store"] = store
		pageData["total"] = total
		jsonByte, _ := json.Marshal(&pageData)
		models.Rdb.Set(keys, string(jsonByte), 0)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-m",
			Data: pageData,
		}
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-r",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
